/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.cryptography.providers;

import io.iec.edp.caf.commons.cryptography.service.HashProvider;
import org.bouncycastle.crypto.digests.SM3Digest;
import io.iec.edp.caf.commons.utils.ByteUtils;
import java.nio.charset.StandardCharsets;

/**
 * SM3国产散列算法
 * @author wangyandong
 */
public class SM3Provider implements HashProvider {

    /**
     * 计算散列值
     *
     * @param data 输入字节数组
     * @return 散列值
     */
    @Override
    public byte[] createHash(byte[] data) {
        return computeSM3Hash(data);
    }

    /**
     * 计算散列值
     *
     * @param data 输入字节数组
     * @param salt   盐值
     * @return 散列值
     */
    @Override
    public byte[] createHash(byte[] data, byte[] salt) {
        return computeSM3Hash(ByteUtils.concatenate(data, salt));
    }

    /**
     * SM3 字符串
     *
     * @param data 输入数据
     * @return 16进制散列值
     */
    @Override
    public String createHash(String data) {
        return ByteUtils.toHexString(createHash(data.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * SHA256 字符串
     *
     * @param data 输入数据
     * @param salt 盐值
     * @return 16进制散列值
     */
    @Override
    public String createHash(String data, String salt) {
        byte[] dataWithSalt = (data + salt).getBytes(StandardCharsets.UTF_8);
        return ByteUtils.toHexString(createHash(dataWithSalt));
    }

    /**
     * 国产加密算法SM3实现
     * 这里使用了bcprov-jdk15on-1.59这个jar包
     *
     * @param data 输入数据
     * @return 散列值
     */
    private byte[] computeSM3Hash(byte[] data) {
        SM3Digest digest = new SM3Digest();
        digest.update(data, 0, data.length);
        byte[] result = new byte[digest.getDigestSize()];
        digest.doFinal(result, 0);
        return result;
    }
}